import { AxiosResponse, AxiosStatic, InternalAxiosRequestConfig } from 'axios'
import { useRouter } from 'vue-router'
import { getStorage } from '@/utils/localstorage'
import { TOKEN } from '@/constants/constants'
import { AuthEroor, GetwayEroor, RequestStatus } from '@/enums/http'
import { settingLoading } from '@/utils'

const router = useRouter()
// 设置token到请求头中
const setTokenToRequestHeader = (config: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
  const token = getStorage(TOKEN)
  config.headers = config.headers || {}
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}

const exportFileTypeList = [
  'application/vnd.ms-excel;charset=utf-8',
  'application/vnd.ms-excel;charset=UTF-8',
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
]
// 预处理响应的内容
const successHooks = (res: AxiosResponse<any>): AxiosResponse<any> | Promise<any> => {
  if (res.data.code !== RequestStatus.SUCCESS) {
    if (exportFileTypeList.indexOf(res.headers['content-type']) > -1) {
      return res
    }
    if (res.status in RequestStatus || res.data.code in RequestStatus) {
      router.push(`/error/${res.data.code || RequestStatus.NOT_AUTHORIZED.toString()}`)
    } else if (res.data.code in GetwayEroor) {
      router.push(`/error${res.data.code}`)
    } else if (res.data.code in AuthEroor) {
      router.push('/error/401')
    }
    // eslint-disable-next-line prefer-promise-reject-errors
    return Promise.reject({ message: res.data.message })
  }
  return res
}

// 错误异常处理钩子
const errorHooks = (error: any): Promise<any> => {
  settingLoading(false)
  if (error.message === 'interrupt') {
    return Promise.reject(error)
  }
  if (error.response) {
    const res = error.response
    if (res.status === 500) {
      router.push('/error/500')
    } else if (error.response.status in RequestStatus) {
      router.push(`/error/${error.response.status || RequestStatus.NOT_AUTHORIZED.toString()}`)
    }
  }
  return Promise.reject(error)
}

// 请求拦截器
export const useRequestInterceptor = (ax: AxiosStatic): void => {
  ax.interceptors.request.use(
    (config) => setTokenToRequestHeader(config),
    (error) => Promise.reject(error),
  )
}

// 响应拦截器
export const useResponseInterceptor = (ax: AxiosStatic): void => {
  ax.interceptors.response.use(
    (res) => successHooks(res),
    (error) => errorHooks(error),
  )
}
